import { NextRequest, NextResponse } from 'next/server';
import { db } from '@/lib/mysql';
import { verifyToken } from '@/lib/auth';
import { QUESTION_BANK } from '@questions';

console.log('📦 QUESTION_BANK导入结果:', QUESTION_BANK ? `成功 (${Object.keys(QUESTION_BANK).length}个知识点)` : '失败 - undefined');

// 获取下一个待检测题目
export async function GET(request: NextRequest) {
  try {
    // 验证管理员权限
    const token = request.cookies.get('token')?.value;
    console.log('🔐 检查token:', token ? '存在' : '不存在');
    
    if (!token) {
      console.log('❌ 未找到token cookie');
      return NextResponse.json({ error: '未登录' }, { status: 401 });
    }

    const payload = verifyToken(token);
    console.log('👤 Token验证结果:', payload);
    
    if (!payload || payload.role !== 'admin') {
      console.log('❌ 权限不足:', payload?.role);
      return NextResponse.json({ error: '无权限' }, { status: 403 });
    }

    const userId = payload.userId;

    // 获取查询参数
    const searchParams = request.nextUrl.searchParams;
    const mode = searchParams.get('mode') || 'all'; // all, topic, problem
    const topicId = searchParams.get('topicId');

    // 构建所有题目列表
    const allQuestions: Array<{
      questionId: string;
      topicId: string;
      topicName: string;
      questionIndex: number;
      question: any;
    }> = [];

    for (const [topic, questions] of Object.entries(QUESTION_BANK)) {
      // 如果是知识点模式，只获取指定知识点
      if (mode === 'topic' && topicId && topic !== topicId) {
        continue;
      }

      questions.forEach((q, index) => {
        allQuestions.push({
          questionId: `${topic}:${index}`,
          topicId: topic,
          topicName: topic,
          questionIndex: index,
          question: q
        });
      });
    }

    // 获取已检测的题目
    const reviewedResult = await db.query(
      `SELECT question_id, status FROM question_reviews 
       WHERE reviewed_by = ? AND status != 'pending'`,
      [userId]
    ) as any;

    console.log('📊 数据库查询结果:', reviewedResult);
    
    // mysql2返回的是数组，不需要解构
    const reviewed = Array.isArray(reviewedResult) ? reviewedResult : [];
    
    const reviewedSet = new Set(reviewed.map((r: any) => r.question_id));
    const reviewedCorrect = new Set(
      reviewed.filter((r: any) => r.status === 'correct').map((r: any) => r.question_id)
    );

    // 根据模式过滤题目
    let filteredQuestions = allQuestions;

    if (mode === 'problem') {
      // 问题复查模式：只显示标记为有问题的题目
      const problemsResult = await db.query(
        `SELECT question_id FROM question_reviews 
         WHERE reviewed_by = ? AND status IN ('incorrect', 'marked')`,
        [userId]
      ) as any;
      const problems = Array.isArray(problemsResult) ? problemsResult : [];
      const problemSet = new Set(problems.map((p: any) => p.question_id));
      filteredQuestions = allQuestions.filter(q => problemSet.has(q.questionId));
    } else {
      // 普通模式：过滤已答对的题目
      filteredQuestions = allQuestions.filter(q => !reviewedCorrect.has(q.questionId));
    }

    // 获取第一个未检测的题目
    const nextQuestion = filteredQuestions[0];

    if (!nextQuestion) {
      return NextResponse.json({
        completed: true,
        message: '所有题目已检测完成！',
        total: allQuestions.length,
        reviewed: reviewedSet.size
      });
    }

    // 验证题目数据
    if (!nextQuestion.question) {
      console.error('题目数据缺失:', nextQuestion);
      return NextResponse.json({ 
        error: '题目数据加载失败',
        details: 'Question data is missing'
      }, { status: 500 });
    }

    // 统计信息
    const stats = {
      total: allQuestions.length,
      reviewed: reviewedSet.size,
      remaining: allQuestions.length - reviewedCorrect.size,
      currentIndex: allQuestions.findIndex(q => q.questionId === nextQuestion.questionId) + 1
    };

    return NextResponse.json({
      question: nextQuestion.question,
      questionId: nextQuestion.questionId,
      topicId: nextQuestion.topicId,
      topicName: nextQuestion.topicName,
      questionIndex: nextQuestion.questionIndex,
      stats
    });

  } catch (error: any) {
    console.error('获取下一题失败:', error);
    return NextResponse.json({ error: error.message }, { status: 500 });
  }
}

